var mongoose = require('mongoose');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID; // mogodb的ObjectId对象 查询数据使用
var assert = require('assert');
var fs = require('fs'); // fs 读取文件
var multer = require('multer'); // 上传图片

// 数据库地址
var url = 'mongodb://localhost:27017';

// Database Name 数据库名称
var dbName = 'config';
var db;
var collection;
// Use connect method to connect to the server
MongoClient.connect(url, function (err, client) {
    assert.equal(null, err);
    console.log('数据库链接成功.....');
    db = client.db(dbName);

console.log(db);

});

var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
};


var uploadFolder = './upload/'; // 上传图片保存目录

createFolder(uploadFolder); // 是否创建文件夹

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder);
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});

var upload = multer({ storage: storage });

// 查询swiper的数据
// var swiperList = function (db, callback) {
//     // Get the documents collection
//     collection = db.collection('swiper');
//     // Find some documents
//     collection.find({}).toArray(function (err, docs) {
//         // assert.equal(err, null);
//         // console.log(docs)
//         callback(docs);
//     });
// }

// 封装数据查询的方法
/**
 * @param {*} _id id查询数据
 * @param {*} db 当前的数据库名称
 * @param {*} tablename 当前的表名
 * @param {*} callback 回调取值
 */
var getcomData = function (_id, db, tablename, callback) {
    // Get the documents collection
    collection = db.collection(tablename);
    // Find some documents
    collection.find(_id).toArray(function (err, docs) {
        callback(docs);
    });
}


//定义数据模型
// var personalInfo = new mongoose.Schema({
//     name: String,
//     hobby: String,
//     address: String,
//     livesong: String,
//     detailed: String,
// })

// mongoose.model('personalInfo', personalInfo);//将该Schema发布为Model,第一个参数为数据库的集合，没有会自动创建

// var personal = mongoose.model('personalInfo'); //personal name

// mongoose.Promise = global.Promise;  //为了避免警告的出现，因为mongoose的默认promise已经弃用了

// 上传明星照片及基本数据 
var upLoadStar = function (db, star, callback) {
    // Get the documents collection
    collection = db.collection('personalInfo');
    // Insert some documents
    console.log('star', star)
    collection.insertMany(star, function (err, result) {
        callback(result);
    });
}

/**
 * @param {*} db 当前的数据库名称
 * @param {*} page 当前页数
 * @param {*} rows 一页几条
 */
var pageIndex = function (db, page, rows, res) {
}

// 解决跨域 https://www.cnblogs.com/king-ying/p/7248816.html
module.exports = function (app) {
    app.all("*", function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        res.header("X-Powered-By", ' 3.2.1')
        if (req.method == "OPTIONS") res.send(200);/*让options请求快速返回*/
        else next();
    });
    // 首页轮播图
    app.get('/swiper', function (req, res) {
        if (db) {
            getcomData({}, db, 'swiper', function (data) {
                res.send(data[0])
            });
        }
    })
    // 上传图片及明星基本信息 
    app.post('/upload/star', upload.single('logo'), function (req, res) {
        var result = req.body;
        var uploadObj = [{
            logo: req.file.filename,
            name: result.name,
            hobby: result.hobby,
            address: result.address,
            livesong: result.livesong,
            detailed: result.detailed,
        }]
        if (db) {
            upLoadStar(db, uploadObj, function (data) {
                res.send('-完成')
            })
        }
    });

    // 获取明星列表
    app.get('/upload/starList', function (req, res) {
        if (db) {
            getcomData({}, db, 'personalInfo', function (data) {
                res.send(data)
            });
        }
    })

    // 获取单个明星详细信息
    app.get('/single/starInfor', function (req, res) {
        if (db) {
            getcomData({ _id: ObjectID(req.query['_id']) }, db, 'personalInfo', function (data) {
                res.send(data[0])
            })
        }
    })

    // 实现分页查询
    app.post('/index/pagelist', function (req, res) {
        var page = Number(req.body.page);
        var rows = Number(req.body.rows);
        if (db) {
            collection = db.collection('personalInfo');
            collection.find().skip((page - 1) * rows).limit(rows).toArray(function (err, docs) {
                collection.find().toArray(function(err,result){
                    jsonArray={rows:docs,total:result.length};
                    res.json(jsonArray);
                })
            })
        }
    })
}